package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.CodeBean;
import com.zhongjian.technologycal.mall.bean.CodeResBean;
import com.zhongjian.technologycal.mall.http.BaseSubscriber;
import com.zhongjian.technologycal.mall.http.ExceptionHandle;
import com.zhongjian.technologycal.mall.http.MyApiService;
import com.zhongjian.technologycal.mall.http.RetrofitClient;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.Countdown;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.PasswordInputView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/14.
 * 设置支付密码
 */

public class SettingPayPasswordActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.paypassword_tv_commit_code)
    TextView paypassword_tv_commit_code;
    @BindView(R.id.paypassword_et_code)
    EditText paypassword_et_code;
    @BindView(R.id.paypassword_tv_phone)
    TextView paypassword_tv_phone;
    private Dialog hintDialog = null;
    private String veriyCode = null;
    private String username;

    @Override
    protected void beforeInit() {
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("设置支付密码");
        username = getIntent().getStringExtra("username");
        paypassword_tv_phone.setText(username);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_setting_password;
    }

    @Override
    public void initPresenter() {

    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    @OnClick(R.id.paypassword_tv_commit_code)
    public void onClickCommitCode() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        new Countdown(paypassword_tv_commit_code, 60, "秒后重试", false);
        paypassword_tv_commit_code.setClickable(false);
        MyApiService service = RetrofitClient.getInstance(getBaseContext()).create(MyApiService.class);
        Map<String, String> maps = new HashMap<String, String>();
        maps.put("phoneNum", username);
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));

        // execute and add observable to RxJava
        RetrofitClient.getInstance(getBaseContext()).createBaseApi().execute(
                service.jsonSendCode(body), new BaseSubscriber<CodeBean>(getBaseContext()) {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(SettingPayPasswordActivity.this);
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        Log.e("Lyk", e.getMessage());

                    }

                    @Override
                    public void onNext(CodeBean codeBean) {
                        LoadingDialog.cancelDialogForLoading();
                        if (codeBean.getError_code() == 0) {
                            ToastUitl.showShort(codeBean.getError_message());

                        } else {
                            new Countdown(paypassword_tv_commit_code, 0, "秒后重试", false);
                            paypassword_tv_commit_code.setClickable(true);
                            ToastUitl.showShort(codeBean.getError_message());
                        }

                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        LoadingDialog.cancelDialogForLoading();
                    }
                });


    }

    @OnClick(R.id.paypassword_tv_commit)
    public void onClickSettingCommit() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        } else if (TextUtils.isEmpty(paypassword_et_code.getText().toString().trim())) {
            ToastUitl.showShort("验证码不能为空～");
            return;
        }

        Map<String, String> maps = new HashMap<String, String>();
        maps.put("token", UserUtils.getUserToken());
        maps.put("verifyCode", paypassword_et_code.getText().toString().trim());
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestPayVerify(body, new Subscriber<ResponseBody>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(ResponseBody responseBody) {
                try {
                    Gson gson = new Gson();
                    CodeResBean baseBean = gson.fromJson(responseBody.string(), CodeResBean.class);
                    if (baseBean.getError_code() == 0) {
                        veriyCode = baseBean.getData();
                        initViewDialog();
                    } else {
                        ToastUitl.showShort(baseBean.getError_message());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

    }

    private void initViewDialog() {
        hintDialog = new Dialog(SettingPayPasswordActivity.this, R.style.dialog_style1);
        LinearLayout layout;
        LayoutInflater inflater = (LayoutInflater) SettingPayPasswordActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                null);
        final PasswordInputView tv_hint = (PasswordInputView) layout
                .findViewById(R.id.again_paypswd_pet);
        TextView textView = layout.findViewById(R.id.dialog_tv_title);
        textView.setText("设置支付密码");
        layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        hintDialog.dismiss();
                    }
                });
        layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                            ToastUitl.showShort("请输入支付密码");
                            return;
                        } else if (tv_hint.getText().toString().trim().length() < 6) {
                            ToastUitl.showShort("请输入6位支付密码");
                            return;
                        }

                        initRequestPayPassword(veriyCode, tv_hint.getText().toString().trim());

                    }
                });
        hintDialog.setContentView(layout);
        hintDialog.show();

    }

    private void initRequestPayPassword(String payPasswordCertificate, String payPassword) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }

        Map<String, String> maps = new HashMap<String, String>();
        maps.put("paypassword", payPassword);
        maps.put("token", UserUtils.getUserToken());
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestSettingPayPassword(payPasswordCertificate,
                        body, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(SettingPayPasswordActivity.this);
                            }

                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();
                            }

                            @Override
                            public void onError(Throwable e) {
                                ToastUitl.showShort(e.getMessage());
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        SettingPayPasswordActivity.this.finish();
                                    } else if (baseBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
    }
}
